package club.jdiy.admin.entity;

import club.jdiy.core.base.domain.JpaEntity;
import club.jdiy.core.base.domain.Sortable;
import club.jdiy.core.base.DslFilter;
import club.jdiy.core.base.domain.DslFilterable;
import com.querydsl.core.BooleanBuilder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.*;
import java.util.List;

@Entity
@Table(name = "jdiy_dict")
@NoArgsConstructor
@Data
public class Dict implements JpaEntity<String>, Sortable, DslFilterable {
    @Id
    @Column(length = 24)
    private String id;
    @Column(length = 50)
    private String name;//字典名
    @Column(columnDefinition = "int default 100 not null")
    private Integer sortIndex=100;
    @Column(columnDefinition = "text")
    private String remark;//备注

    @Column(columnDefinition = "tinyint(1)")
    private int type;// 1:只有key   2: key/value   3: key/value/color

    @Column(length = 30, nullable = false)
    private String keyName="名称";//键名
    @Column(length = 30, nullable = false)
    private String valName="值";//键值

    @Column(columnDefinition = "bit default 0 not null")
    private Boolean hidden;//对(非开发者)隐藏
    @Column(columnDefinition = "bit default 1 not null")
    private Boolean editable;//(非开发者)是否允许修改条目
    @Column(columnDefinition = "bit default 1 not null")
    private Boolean addable;//(非开发者)是否允许添加新条目
    @Column(columnDefinition = "bit default 1 not null")
    private Boolean removable;//(非开发者)是否允许删除条目

    //autovalues=true 表示字典值由系统自动生成，管理员用户无法更改
    // 类似于普通表的自增id,好处是避免用户乱改key导致业务异常
    @Column(columnDefinition = "bit default 0 not null")
    private Boolean autovalues;

    @OneToMany(mappedBy = "dict",cascade = CascadeType.REMOVE)
    private List<DictItem> items;

    public Dict(String id) {
        this.id = id;
    }

    @PreUpdate
    @PrePersist
    private void init(){
        if(sortIndex==null)sortIndex=100;
    }
    @Override
    public DslFilter createFilter(BooleanBuilder builder) {
        QDict qo = QDict.dict;
        if (hidden != null) builder.and(qo.hidden.eq(hidden));

        return new DslFilter(builder, qo.sortIndex.asc());
    }
}
